package com.travel.admin.thread;

import com.travel.admin.exception.TravelExceptionCode;
import com.travel.admin.util.prewarn.ChatBotSend;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 * @desc:  微服务预警 线程
 */
public class PreWarnThread implements Runnable {

    private Logger logger = LoggerFactory.getLogger(PreWarnThread.class);

    private String method;
    private ChatBotSend chatBotSend;

    private TravelExceptionCode zlcpdExceptionCode;
    private Integer limitNum;

    private RedisTemplate redisTemplate;
    public PreWarnThread(ChatBotSend chatBotSend, RedisTemplate redisTemplate, String method,
                         TravelExceptionCode zlcpdExceptionCode,Integer limitNum){
        this.redisTemplate = redisTemplate;
        this.chatBotSend = chatBotSend;
        this.method = method;
        this.zlcpdExceptionCode = zlcpdExceptionCode;
        this.limitNum = limitNum;
    }

    @Override
    public void run() {
        try {
            // 钉钉 群预警消息
            Long result = redisTemplate.opsForValue().increment(method,1L);
            redisTemplate.expire(method,10, TimeUnit.MINUTES);
            //单个接口在10分钟内 大于n次熔断，则进行预警通知
            limitNum = null == limitNum?5:limitNum;
            if(null != result && result > 5 && result<8){
                chatBotSend.sendMsg(method, zlcpdExceptionCode);
            }
            // Todo
            // 短信消息通知
            // 邮件通知

        } catch (Exception e) {
            logger.warn("PreWarnThread,warn");
        }
    }
}
